package com.andy.blog.admin.service.impl;

import com.andy.blog.admin.dto.login.CaptchaDTO;
import com.andy.blog.admin.service.CaptchaBusService;
import com.andy.blog.admin.service.ConfigBusService;
import com.andy.blog.common.constant.BaseConstants;
import com.andy.blog.common.constant.CacheConstants;
import com.andy.blog.common.constant.ConfigCenterConstants;
import com.andy.blog.common.constant.FileTypeConstant;
import com.andy.blog.common.core.redis.RedisCache;
import com.andy.blog.common.enums.CaptchaEnum;
import com.andy.blog.common.exception.BlogServiceException;
import com.andy.blog.common.utils.sign.Base64;
import com.andy.blog.dal.vo.EmailCaptchaVO;
import com.andy.blog.integration.service.MailIntegrationService;
import com.andy.blog.integration.vo.SimpleMailVO;
import com.google.code.kaptcha.Producer;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by andy on 2023/4/8 20:40
 */
@Service
public class CaptchaBusServiceImpl implements CaptchaBusService {

    @Resource
    private RedisCache redisCache;

    @Autowired
    private ConfigBusService configBusService;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Resource
    private MailIntegrationService mailIntegrationService;

    @Override
    public CaptchaDTO getCaptchaImage() {

        CaptchaDTO captchaDTO = new CaptchaDTO();
        // 获取验证码配置 是否展示开关
        boolean captchaEnabled = configBusService.selectCaptchaEnabled();
        captchaDTO.setCaptchaEnabled(captchaEnabled);
        if (Boolean.FALSE.equals(captchaEnabled)) {
            return captchaDTO;
        }

        // 保存验证码信息
        String uuid = UUID.randomUUID().toString();

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr;
        String code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = configBusService.selectConfigByKey(ConfigCenterConstants.CAPTCHA_TYPE);
        if (CaptchaEnum.MATH.getCode().equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if (CaptchaEnum.CHAR.getCode().equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, BaseConstants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            assert image != null;
            ImageIO.write(image, FileTypeConstant.JPG_SMALL, os);
        } catch (IOException e) {
            throw new BlogServiceException(e.getMessage());
        }

        captchaDTO.setUuid(uuid);
        captchaDTO.setImg(Base64.encode(os.toByteArray()));
        return captchaDTO;
    }

    @Override
    public String sendEmailByCode(EmailCaptchaVO emailCaptchaVO) {

        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 6);

        SimpleMailVO simpleMailVO = new SimpleMailVO();
        simpleMailVO.setReceiver(Lists.newArrayList(emailCaptchaVO.getEmail()));
        simpleMailVO.setSubject("用户注册");
        simpleMailVO.setContent(code);

        String verifyKey = CacheConstants.PORTAL_CAPTCHA_CODE_KEY + emailCaptchaVO.getUuid();

        redisCache.setCacheObject(verifyKey, code, BaseConstants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        mailIntegrationService.sendSimpleMail(simpleMailVO);

        return emailCaptchaVO.getUuid();
    }
}
